import React, {Component} from 'react';
import {Table, Pagination, Loading} from '@icedesign/base';
import IceContainer from '@icedesign/container';
import Filter from './TableFilter';
import {getTableData} from '../../../../api/index'
import DataBinder from '@icedesign/data-binder';
import EditDialog from "./EditDialog";
import DeleteBalloon from "./DeleteBalloon";
import CustomTable from './CustomTable'
import {Feedback} from '@icedesign/base';

export const NameMap = {
  'STA_NAME': '车站名称',
  'STA_LINENAME': '线路名称',
  'OUCode': '机构代码',
  'OUName': '机构名称',
  'STA_ORDER': 'STA_ORDER',
  'STA_ATTRIB': 'STA_ATTRIB',
};


@DataBinder({ // todo 必须和下面的 组件类 挨着写
  SendData: { // SendData 是 key, 区别不同
    url: '/api/getStaData',
    method: 'post',
    data: {       // todo 发送参数的格式
      current: 1,
      pageSize: 10,
      staName: [],
      ouName: [],
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      data: {
        ListResult: [],
        current: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  updateData: { // UpdateData 是 key, 区别不同
    url: '/api/updateStaData',
    method: 'post',
    data: {       // todo 发送参数的格式
      values: {
        ImgExtensionName: null,
        IsImgDelete: null,
        OUCode: "102023004",
        OUName: "襄阳信息维护工区",
        STA_ATTRIB: "6502",
        STA_ID: "WHBUR_XYSEG_1001",
        STA_LINEID: "WHBUR_XYSEG_LINE_13839",
        STA_LINENAME: "东桥",
        STA_NAME: "东桥",
        STA_ORDER: 7,
        point: null,
        points: null,
        rootIp: null,
        zoom: null,
      }
    },
    success: (res, defaultCallback, originResponse) => {
      // console.log('请求成功了，返回的数据为', res)
      // console.log("orginResponse",originResponse)
      // 执行默认的逻辑请求成功逻辑
      // 通常为弹出反馈 Toast
      if (res.status == 200) {
        Feedback.toast.success("data update success")
      } else {
        Feedback.toast.error("data update fail")
      }
      defaultCallback(); // 没有找到是哪里执行
      // originResponse 内容请参见：https://github.com/axios/axios#response-schema
    },
    error: (res, defaultCallback, originResponse) => {
      // console.log("err",'res', res, originResponse);
      // alert("data update fail",originResponse.statusText)
      Feedback.toast.error("data update fail",originResponse.statusText);
      defaultCallback();
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      data: {
        ListResult: [],
        current: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  delData: { //  key, 区别不同
    url: '/api/delStaData',
    method: 'post',
    data: {       // todo 发送参数的格式
      values: {
        ImgExtensionName: null,
        IsImgDelete: null,
        OUCode: "102023004",
        OUName: "襄阳信息维护工区",
        STA_ATTRIB: "6502",
        STA_ID: "WHBUR_XYSEG_1001",
        STA_LINEID: "WHBUR_XYSEG_LINE_13839",
        STA_LINENAME: "东桥",
        STA_NAME: "东桥",
        STA_ORDER: 7,
        point: null,
        points: null,
        rootIp: null,
        zoom: null,
      }
    },
    success: (res, defaultCallback, originResponse) => {
      // console.log('删除成功，返回的数据为', res)
      // console.log("orginResponse",originResponse)
      // 执行默认的逻辑请求成功逻辑
      // 通常为弹出反馈 Toast
      if (res.status == 200) {
        Feedback.toast.success("data del success");
      } else {
        Feedback.toast.error("data del fail");
      }
      defaultCallback(); // 没有找到是哪里执行
      // originResponse 内容请参见：https://github.com/axios/axios#response-schema
    },
    error: (res, defaultCallback, originResponse) => {
      // console.log("err",'res', res, originResponse);
      Feedback.toast.error("data del fail",originResponse.statusText)
      defaultCallback();
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      data: {
        ListResult: [],
        current: 1,
        total: 0,
        pageSize: 10
      }
    }
  }
})

export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    // let page = {current: 1, pageSize: 10, years: [], deviceType: []};
    this.state = { // 默认分页数据
      current: 1,
      pageSize: 10,
      data: {},
      staName: [],
      ouName: []
    }

    this.columns = [
      {
        title: NameMap['STA_NAME'],
        dataIndex: 'STA_NAME',
        key: 'STA_NAME',
      },
      {
        title: NameMap['STA_ATTRIB'],
        dataIndex: 'STA_ATTRIB',
        key: 'STA_ATTRIB',
      },
      {
        title: NameMap['STA_LINENAME'],
        dataIndex: 'STA_LINENAME',
        key: 'STA_LINENAME',
      },
      {
        title: NameMap['OUCode'],
        dataIndex: 'OUCode',
        key: 'OUCode',
      },
      {
        title: NameMap['OUName'],
        dataIndex: 'OUName',
        key: 'OUName',
      },
      {
        title: NameMap['STA_ORDER'],
        dataIndex: 'STA_ORDER',
        key: 'STA_ORDER',
      },
      {
        title: '操作',
        key: 'action',
        render: (value, index, record) => {
          // console.log(value, index, record) // value: 不清楚false， index是数组序号 0，  record是一条数据，{id: 1, YMonth: "2018", DeviceType: "106100", STA_NAME: "信阳驼峰站", ORG1_ID: "103", …}
          return (
            <span>
              <EditDialog
                // index={index}
                // index={record.STA_ID} // id值方便回传
                record={record}
                updateFormValues={this.updateFormValues} // todo 绑定弹窗的方法
              />
              <DeleteBalloon
                handleRemove={() => this.handleRemove(value, index, record)}
              />
            </span>
          );
        },
      },
    ];
  }

  handleRemove = (value, index, record) => {
    console.log(value, index, record)
    this.props.updateBindingData('delData', {
      data: {
        values: record,
        // state:{...this.state}
      }
    }, (response) => {
      console.log(response)
      this.props.updateBindingData('SendData', { // 更新完数据，callback 刷新数据
        data: {   // 发送参数
          current: 1,
          pageSize: this.state.pageSize,
          staName: this.state.staName,
          ouName: this.state.ouName,
        }
      });
    });
  };

  updateFormValues = (values) => {
    // console.log(values)
    this.props.updateBindingData('updateData', {
      data: {
        values: values,
        // state:{...this.state}
      }
    }, (response) => {
      console.log(response)
      this.props.updateBindingData('SendData', { // 更新完数据，callback 刷新数据
        data: {   // 发送参数
          current: 1,
          pageSize: this.state.pageSize,
          staName: this.state.staName,
          ouName: this.state.ouName,
        }
      });
    });

  };

  RecvFormData({ouName, staName}) { // 组件通信
    console.log(ouName, staName);
    let ouNamearr
    let sta


    if (ouName == undefined || ouName == "") {
      ouNamearr = []
    } else {
      ouNamearr = []
      ouNamearr.push(ouName)
    }



    if (staName == undefined || staName == "") {
      sta = []
    } else {
      sta = []
      sta.push(staName)
    }

    this.setState({
      ouName: ouNamearr,
      staName: sta
    });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: 1,
        pageSize: this.state.pageSize,
        ouName: ouNamearr,
        staName: sta,
      }
    }, function (res) {
      console.log(res)
    });
  }

  componentDidMount() {
    // todo 使用databinder 默认数据第一次渲染，初始化第一页的数据

    // 使用DataBinder 中默认的 发送参数
    this.props.updateBindingData('SendData');
  }

  handlePaginationChange = (current) => { // 改变页码函数,current自动传入
    // this.setState({ // 页码保存
    //   current: current
    // });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: current,
        pageSize: this.state.pageSize,
        ouName: this.state.ouName,
        staName: this.state.staName
      }
    });
  };

  handlePageSizeChange = (pagesize) => { // 改变显示个数
    this.setState({
      pageSize: pagesize // 显示个数保存
    });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: 1, // 显示的个数多以后 ，可能会没有超过当前页
        pageSize: pagesize,
        ouName: this.state.ouName,
        staName: this.state.staName
      }
    });
  };


  // renderOper = () => {
  //   return (
  //     <div>
  //       <a style={styles.link}>详情</a>
  //       <span style={styles.separator}/>
  //       <a style={styles.link}>申请权限</a>
  //     </div>
  //   );
  // };

  render() {
    // console.log(11111111, this.props.bindingData)
    const dataSource = this.props.bindingData.SendData; // SendData 是 binder方法的key
    // console.log(22222222,dataSource);

    // todo CustomTable 是包装一层返回的table组件， 同时生成列头
    // Loading 加载动画
    return (
      <IceContainer style={styles.container}>
        <h4 style={styles.title}>测试数据</h4>
        <Filter filterData={this.RecvFormData.bind(this)} ouName={this.state.ouName}/>
        <Loading visible={dataSource.__loading} shape="fusion-reactor">
          <div>
            <CustomTable
              dataSource={dataSource.ListResult}
              columns={this.columns}
              hasBorder={false}
              isLoading={this.props.bindingData.__loading}
              // optimization={false}
            />

            <Pagination
              style={styles.pagination}
              current={dataSource.current}
              pageSizeSelector='filter'
              total={dataSource.total}
              pageSize={dataSource.pageSize}
              onChange={this.handlePaginationChange} // 点击页码的 函数
              onPageSizeChange={this.handlePageSizeChange}  // 点击每页显示多少的 函数
            />
          </div>
        </Loading>
      </IceContainer>
    );
  }
}

const styles = {
  container: {
    margin: '20px',
    padding: '0 0 20px',
  },
  title: {
    margin: '0',
    padding: '15px 20px',
    fonSize: '16px',
    textOverflow: 'ellipsis',
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    color: 'rgba(0,0,0,.85)',
    fontWeight: '500',
    borderBottom: '1px solid #eee',
  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 8px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    textAlign: 'right',
    marginRight: '20px',
  },
};
